package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    //新增床位
    @Override
    public void insertBed(BedDto bedDto) {

        //判断床位编号不能重复
        Bed bedNumber= bedMapper.getBedNumber(bedDto.getBedNumber());
        if (bedNumber!=null){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_DUPLICATE_NUMBER);
        }
        Bed bed = new Bed();
        BeanUtils.copyProperties(bedDto,bed);
        bed.setBedStatus(0);
        bed.setCreateBy(1L);
        bed.setCreateTime(LocalDateTime.now());
        bedMapper.insertBed(bed);
    }

    //根据ID查询床位 回显
    @Override
    public BedVo selectById(Long id) {
        return  BeanUtil.toBean(bedMapper.selectById(id), BedVo.class);
    }

    //更新床位
    @Override
    public void updateById(BedDto bedDto) {
        //判断状态必须是0 才能修改
        BedVo bedVo = bedMapper.selectById(bedDto.getId());
        if (bedVo.getBedStatus() != 0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_NUMBER_STATUS);
        }
        //修改时候判断床位编号不能重复，同时也不能跟自己重复
        Long count= bedMapper.getNumber(bedDto.getBedNumber(),bedDto.getId());
        if (count>0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_NUMBER);
        }
        Bed bed = BeanUtil.toBean(bedDto, Bed.class);
        bedMapper.updateById(bed);
    }

    //5.3.4 删除床位
    @Override
    public void deleteById(Long id) {
        bedMapper.deleteById(id);
    }

}

